
#include "Level.h"

std::vector<CBloco> Level::blocosList;
int Level::objectiveBricks = 0;

Level::Level(){

}

bool Level::onInit(){
	
	if(!normalBrick.onLoad("images/brick.png"))
		return false;
	normalBrick.setObjectiveBrick(true);

	if(!solidBrick.onLoad("images/sbrick.png"))
		return false;
	solidBrick.setSolid(true);

	Texto::textList[LEVEL_TEXT_INDEX]->setText("Level: 1");

	setLevel(1);
	return true;
}

bool Level::onLoad(int lv){
	
	char str[18];

	sprintf_s(str,"levels/%d.level",level);

	return onLoad(str);
}

bool Level::onLoad(char *file){
	
	std::ifstream levelFile;
	int blockType = 0;
	objectiveBricks = 0;
	
	levelFile.open(file);

	if(levelFile.fail() || !levelFile.good())
		return false;

	for(int row=0; row < 24; row++)
	{
		for(int col=0; col< 16; col++)
		{
			levelFile >> std::skipws >> blockType;
			
			if(blockType == NO_BRICK)
				continue;

			switch(blockType)
			{
				case NORMAL_BRICK:
					normalBrick.setBrickSpot(row,col);
					blocosList.push_back(normalBrick);
					objectiveBricks++;
				break;

				case SOLID_BRICK:
					solidBrick.setBrickSpot(row,col);
					blocosList.push_back(solidBrick);
				break;

				default:
					levelFile.close();
					return false;
				break;
			}
		}
	}

	levelFile.close();
	return true;
}

void Level::onLoop(){

	if(objectiveBricks <= 0)
		if(!nextLevel())
			level = -1;
}

void Level::onRender(SDL_Surface* destSurface){
	
	for(unsigned int i=0; i< blocosList.size(); i++)
		blocosList[i].onRender(destSurface);
}

void Level::onCleanup(){
	
	normalBrick.onCleanup();
	solidBrick.onCleanup();

	blocosList.clear();
}

bool Level::setLevel(int lv){
	
	if(lv <= 0)
		return false;

	level = lv;
	blocosList.clear();

	if(onLoad(level))
	{
		char str[15];
		sprintf_s(str,"Level: %d",level);
		Texto::textList[LEVEL_TEXT_INDEX]->setText(str);

		return true;
	}
	else
		return false;

}

bool Level::nextLevel(){
	return setLevel(++level);
}

int Level::getCurrentLevel(){
	return level;
}